package cn.cloud.all.security.authentication;

import cn.cloud.all.security.authentication.exception.AccountExpiredException;
import cn.cloud.all.security.authentication.exception.CredentialsExpiredException;
import cn.cloud.all.security.authentication.exception.DisabledException;
import cn.cloud.all.security.authentication.exception.LockedException;
import cn.cloud.all.security.core.SpringSecurityMessageSource;
import cn.cloud.all.security.core.userdetails.UserDetails;
import cn.cloud.all.security.core.userdetails.UserDetailsChecker;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;

public class AccountStatusUserDetailsChecker implements UserDetailsChecker, MessageSourceAware {

    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    public void check(UserDetails user) {
        if (!user.isAccountNonLocked()) {
            throw new LockedException(messages.getMessage("AccountStatusUserDetailsChecker.locked", "User account is locked"));
        }

        if (!user.isEnabled()) {
            throw new DisabledException(messages.getMessage("AccountStatusUserDetailsChecker.disabled", "User is disabled"));
        }

        if (!user.isAccountNonExpired()) {
            throw new AccountExpiredException(messages.getMessage("AccountStatusUserDetailsChecker.expired", "User account has expired"));
        }

        if (!user.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(messages.getMessage("AccountStatusUserDetailsChecker.credentialsExpired", "User credentials have expired"));
        }
    }

    @Override
    public void setMessageSource(MessageSource messageSource) {
        Assert.notNull(messageSource, "messageSource cannot be null");
        this.messages = new MessageSourceAccessor(messageSource);
    }
}
